package com.sanpu.kxe.business.repay.view;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.repay.adapter.QueryPlanDetailsAdapter;
import com.sanpu.kxe.business.repay.bean.QueryPlanDetailsOutput;
import com.sanpu.kxe.business.repay.contract.QueryPlanDetailsContract;
import com.sanpu.kxe.business.repay.contract.RepayConfig;
import com.sanpu.kxe.business.repay.presenter.QueryPlanDetailsPresenter;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.jump.eventbus.RefreshCancelPlanEvent;
import com.sanpu.kxe.utils.DateUtils;
import com.sanpu.kxe.utils.DialogUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Description：查询计划详情
 * Created by 薛勇军 on 2019/4/10.
 */

public class QueryPlanDetailsActivity extends BaseTitleActivity implements QueryPlanDetailsContract.View {

    @Bind(R.id.planDetailsLv)
    ListView planDetailsLv;
    @Bind(R.id.bottomLl)
    LinearLayout bottomLl;

    private TextView channelNameTv, expectedRepayAmountTv, actualRepayAmountTv, expectedFeeTv, actualFeeTv,
            tradeRateTv, extraChargeTv, refundTv, cardInfoTv, failCauseTv, resultTv;

    private LinearLayout failCauseLl, resultLl;

    private QueryPlanDetailsAdapter planAdapter;

    private QueryPlanDetailsContract.Presenter mPresenter;

    private String repayOrderNo;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_query_plan_details;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("计划明细");

        View headView = LayoutInflater.from(mContext).inflate(R.layout.view_query_plan_details_head, null);
        channelNameTv = ButterKnife.findById(headView, R.id.channelNameTv);
        expectedRepayAmountTv = ButterKnife.findById(headView, R.id.expectedRepayAmountTv);
        actualRepayAmountTv = ButterKnife.findById(headView, R.id.actualRepayAmountTv);
        expectedFeeTv = ButterKnife.findById(headView, R.id.expectedFeeTv);
        actualFeeTv = ButterKnife.findById(headView, R.id.actualFeeTv);
        tradeRateTv = ButterKnife.findById(headView, R.id.tradeRateTv);
        extraChargeTv = ButterKnife.findById(headView, R.id.extraChargeTv);
        refundTv = ButterKnife.findById(headView, R.id.refundTv);
        cardInfoTv = ButterKnife.findById(headView, R.id.cardInfoTv);
        failCauseLl = ButterKnife.findById(headView, R.id.failCauseLl);
        failCauseTv = ButterKnife.findById(headView, R.id.failCauseTv);
        planDetailsLv.addHeaderView(headView);

        View footerView = LayoutInflater.from(mContext).inflate(R.layout.view_query_plan_details_footer, null);
        resultLl = ButterKnife.findById(footerView, R.id.resultLl);
        resultTv = ButterKnife.findById(footerView, R.id.resultTv);
        planDetailsLv.addFooterView(footerView);

        planAdapter = new QueryPlanDetailsAdapter(mContext,
                new ArrayList<QueryPlanDetailsOutput.QueryPlanDetails>());
        planDetailsLv.setAdapter(planAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        repayOrderNo = getIntent().getStringExtra(RepayConfig.INTENT_REPAYORDERNO);
        String planStatus = getIntent().getStringExtra(RepayConfig.INTENT_PLANSTATUS);
        String tradeTime = getIntent().getStringExtra(RepayConfig.INTENT_TRADETIME);
        commonTitle.setTitle("" + DateUtils.dateToString(tradeTime, "MM月dd日") + "计划");
        if (TextUtils.equals("WATING", planStatus) || TextUtils.equals("PROCESING", planStatus)) {
            bottomLl.setVisibility(View.VISIBLE);
        } else {
            bottomLl.setVisibility(View.GONE);
        }
        mPresenter = new QueryPlanDetailsPresenter(this);
        mPresenter.cardPlanDetailList(repayOrderNo);
    }

    @Override
    public void showDataView(QueryPlanDetailsOutput detailsOutput) {
        if (detailsOutput != null && detailsOutput.getPlanDetailList() != null) {
            planAdapter.setOptionalMcc(detailsOutput.isOptionalMcc());
            planAdapter.setNotifyDataChanged(detailsOutput.getPlanDetailList());
            if (!TextUtils.isEmpty(detailsOutput.getChannelName())) {
                channelNameTv.setText("还款通道：" + detailsOutput.getChannelName() + "");
            }
            String cardNo = detailsOutput.getCardNO();
            String cardInfo = detailsOutput.getBankName() +
                    "（" + cardNo.substring(cardNo.length() - 4) + "）";
            if (!TextUtils.isEmpty(cardNo)) {
                refundTv.setText("付款卡片：" + cardInfo + "");
            }
            if (!TextUtils.isEmpty(detailsOutput.getSettleCardInfo())) {
                cardInfoTv.setText("到账卡片：" + detailsOutput.getSettleCardInfo() + "");
            } else {
                cardInfoTv.setText("到账卡片：" + cardInfo + "");
            }
            if (!TextUtils.isEmpty(detailsOutput.getFailCause())) {
                failCauseLl.setVisibility(View.VISIBLE);
                failCauseTv.setText(detailsOutput.getFailCause());
            }
            if (!TextUtils.isEmpty(detailsOutput.getTotalResult())) {
                resultLl.setVisibility(View.VISIBLE);
                resultTv.setText("统计结果：" + detailsOutput.getTotalResult() + "");
            }
            if (!TextUtils.isEmpty(detailsOutput.getExpectedRepayAmount())) {
                expectedRepayAmountTv.setText("预计还款金额：" + detailsOutput.getExpectedRepayAmount() + "元");
            }
            if (!TextUtils.isEmpty(detailsOutput.getActualRepayAmount())) {
                actualRepayAmountTv.setText("实际还款金额：" + detailsOutput.getActualRepayAmount() + "元");
            }
            if (!TextUtils.isEmpty(detailsOutput.getExpectedFee())) {
                expectedFeeTv.setText("预收手续费：" + detailsOutput.getExpectedFee() + "元");
            }
            if (!TextUtils.isEmpty(detailsOutput.getActualFee())) {
                actualFeeTv.setText("实收手续费：" + detailsOutput.getActualFee() + "元");
            }
            if (!TextUtils.isEmpty(detailsOutput.getTradeRate())) {
                tradeRateTv.setText("消费费率：" + detailsOutput.getTradeRate() + "%");
            }
            if (!TextUtils.isEmpty(detailsOutput.getExtraCharge())) {
                extraChargeTv.setText("还款费率：" + detailsOutput.getExtraCharge() + "元/笔");
            }
        }
    }

    private void showFootContent(QueryPlanDetailsOutput detailsOutput) {
        String failCause = "失败原因：";
        if (!TextUtils.isEmpty(detailsOutput.getFailCause())) {
            failCause += detailsOutput.getFailCause();
        }
//        reposeMsgTv.setText(failCause);

        List<QueryPlanDetailsOutput.QueryPlanDetails> queryPlanDetailses = detailsOutput.getPlanDetailList();
        float successMoney = 0, failMoney = 0;
        for (QueryPlanDetailsOutput.QueryPlanDetails queryPlanDetails : queryPlanDetailses) {
            if (TextUtils.equals(RepayConfig.TRADETYPE_PAYMENT, queryPlanDetails.getRepayTradeType())) {
                if (TextUtils.equals("SUCCESS", queryPlanDetails.getPlanDetailStatus())) {
                    if (!TextUtils.isEmpty(queryPlanDetails.getTradeAmount()))
                        successMoney += Float.parseFloat(queryPlanDetails.getTradeAmount());
                } else {
                    if (!TextUtils.isEmpty(queryPlanDetails.getTradeAmount()))
                        failMoney += Float.parseFloat(queryPlanDetails.getTradeAmount());
                }
            }
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("统计结果：截止至最后一笔成功计划，");
        stringBuffer.append(detailsOutput.getBankName());
        stringBuffer.append("尾号");
        stringBuffer.append(detailsOutput.getCardNO().substring(detailsOutput.getCardNO().length() - 4));
        stringBuffer.append("银行卡已成功还款");
        stringBuffer.append(successMoney);
        stringBuffer.append("元，失败还款");
        stringBuffer.append(failMoney);
        stringBuffer.append("元。");
        stringBuffer.append("\r\n");
        stringBuffer.append("如您仍有疑问，请微信关注公众号“金控V服”进行咨询，客服人员将为您解答。");
        resultTv.setText(stringBuffer);
    }

    @OnClick({R.id.deleteRtv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.deleteRtv:
                DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mContext,
                        "是否撤销此次还款计划？", "取消", "确认",
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                mPresenter.cancelPlan(repayOrderNo);
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
                break;
        }
    }

    @Override
    public void showCancelView() {
        mPresenter.cardPlanDetailList(repayOrderNo);
        bottomLl.setVisibility(View.GONE);
        EventBus.getDefault().post(new RefreshCancelPlanEvent());
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    public void setPresenter(QueryPlanDetailsContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }

}
